package com.example.sqlitetest.View.widget;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.sqlitetest.Model.SQLiteDao;
import com.example.sqlitetest.R;

/**
 * Created by l on 2016/12/29.
 */

public class NotedifyActivity extends AppCompatActivity {

    private EditText  mUpdateEdit;
    private Button  mComperBtn, mDeleteBtn, mCancelBtn;
    private int id;
    private Cursor  mCursor;
    private SQLiteDao  mDao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_dify);
        initView();
    }

    private void initView() {
        final Intent intent = getIntent();
        String  data = intent.getStringExtra("data");
        id = intent.getIntExtra("id",id);

        mUpdateEdit = (EditText)findViewById(R.id.et_modify);
        mUpdateEdit.setText(data);
        mDao = new SQLiteDao(this);
        mCursor = mDao.select();

        mComperBtn = (Button)findViewById(R.id.tbn_update);
        mDeleteBtn = (Button)findViewById(R.id.btn_delete);
        mCancelBtn = (Button)findViewById(R.id.btn_back);

        mComperBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateData();
                Intent intent1 = new Intent(NotedifyActivity.this, NoteActivity.class);
                startActivity(intent1);
                finish();
            }
        });

        mDeleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteData();
                Intent intent2 = new Intent(NotedifyActivity.this, NoteActivity.class);
                startActivity(intent2);
                finish();
            }
        });

        mCancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent3 = new Intent(NotedifyActivity.this, NoteActivity.class);
                startActivity(intent3);
                finish();
            }
        });
    }

    private void updateData() {
        if (id == 0){
            Toast.makeText(NotedifyActivity.this, "不能为空", Toast.LENGTH_SHORT).show();
        }else{
            mDao.update(id, mUpdateEdit.getText().toString());
            mCursor.requery();
            id = 0;
        }
    }

    private void deleteData() {
          if (id == 0){
              Toast.makeText(NotedifyActivity.this, "文本框", Toast.LENGTH_SHORT).show();
          }else{
              mDao.delete(id);
              mCursor.requery();
              id = 0;
          }
    }
}
